package com.test.alarm.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WeChatController {

    @SneakyThrows
    @RequestMapping("/sendMsg")
    public void sendMsg() {
        //企业微信群机器人的WebHook地址
        String WEBHOOK_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d1927c35-71a1-4f37-b833-2e8a56e29a59";
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(WEBHOOK_TOKEN);
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        //构建一个json格式字符串textMsg，其内容是接收方需要的参数和消息内容
        JSONObject json = new JSONObject();
        JSONObject tempJson = new JSONObject();
        tempJson.put("context", "这是一条可配置的通知消息!");
        json.put("text", tempJson);
        json.put("msgtype", "text");
        String textMsg = json.toString();

        StringEntity se = new StringEntity(textMsg, "utf-8");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject object = JSONObject.parseObject(result);
            System.out.println(result);
            int backCode = Integer.parseInt(object.get("errcode").toString());
            if (backCode != 0) {
                System.out.println("AAAAAA");
            }
        }
    }

}